package middle_man;


import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Worker extends Thread {
	private LinkedBlockingQueue<Request> Q;
	private Connection connection;
	private boolean _terminate = false;
	
	public Worker(LinkedBlockingQueue<Request> _Q, String db_host) {
		Q = _Q;
		connection = DB.connect(db_host);
	}
	
	public void terminate() {
		_terminate = true;
	}
	
	private void DoRequest(Request r) {
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = connection.createStatement();
			if(r.getSqlQuery().indexOf("create or replace view") == -1) {
				// Usual query
				rs = stmt.executeQuery(r.getSqlQuery());
			} else {
				// A query which needs a view
				String [] pieces = r.getSqlQuery().split(";");
				stmt.execute(pieces[0] + ";");
				stmt.close();
				
				stmt = connection.createStatement();
				rs = stmt.executeQuery(pieces[1] + ";");
			}
			int rowCount = 0;
			while(rs.next()) { 
				rowCount ++; 
			}
			stmt.close();
			stmt = null;
			rs.close();
			rs = null;
			r.getWriter().println("SUCCESS " + rowCount + " rows");
		} catch(SQLException e) {
			System.err.println("Query " + r.getSqlQuery() + "\n FAILED");
			e.printStackTrace();
			r.getWriter().println("FAILED");
		}
		finally {
			if(stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
				}
			}
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
			synchronized(r.getClientHandler()) {
				r.getClientHandler().shouldSleep = false;
				r.getClientHandler().notify();
			}
		}
	}
	
	public void run() {
		this.setName("MiddleMan - Worker thread");
		try {
			Request r;
			while(!_terminate) {
				r = Q.poll(1, TimeUnit.SECONDS);
				if(r!=null) {
					DoRequest(r);
				}
			}
		} catch (InterruptedException e) {
			System.err.println("Worker was interrupted while waiting...");
			e.printStackTrace();
		} finally {
			DB.disconnect(connection);
		}
	}
}
